package com.eshop.controller;

import com.eshop.model.Address;
import com.eshop.model.Order;
import com.eshop.model.OrderDetail;
import com.eshop.model.User;
import com.eshop.model.myPojo.CartGoods;
import com.eshop.service.Impl.OrderServiceImpl;
import com.eshop.service.Impl.UserCenterServiceImpl;
import com.eshop.service.OrderService;
import com.eshop.service.UserCenterService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/orders")
public class OrderController extends HttpServlet {
    UserCenterService userCenterService = new UserCenterServiceImpl();
    OrderService orderService = new OrderServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");

        String action = req.getParameter("action");

        try {
            Method method = this.getClass().getDeclaredMethod(action,HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void getAllOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User)req.getSession().getAttribute("_LOGIN_USER_");

        List<List<OrderDetail>> orderDetailList = new ArrayList<>();

        List<Order> orderList = orderService.getOrderByUserId(user.getUser_id());

        if (orderList != null && orderList.size() != 0) {
            for (Order order : orderList){
                orderDetailList.add(orderService.getOrderDetailByOrderId(order.getOrder_id()));
            }
        }

        req.setAttribute("orderList",orderList);
        req.setAttribute("orderDetailList",orderDetailList);

        req.getRequestDispatcher("/pages/order/order.jsp?action=allOrder").forward(req, resp);
    }

    protected void addOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User)req.getSession().getAttribute("_LOGIN_USER_");
        double priceSum = Double.parseDouble(req.getParameter("priceSum"));
        req.setAttribute("priceSum",priceSum);
        int addressId = Integer.parseInt(req.getParameter("addressId"));

        Address address = userCenterService.getAddressByAddressId(addressId);

        Map<Integer,CartGoods> cartGoodsList = (Map<Integer, CartGoods>) req.getSession().getAttribute("cartGoodsList");

        if (cartGoodsList.size()!=0) {
                    Order order = new Order(0,"20210205124343824000",user.getUser_id(),1,address.getAddr_province()+" "+address.getAddr_city()+" "+address.getAddr_area()+" "+address.getAddr_content()+"（"+address.getAddr_receiver()+"收）"+address.getAddr_tel(),12,new Date(System.currentTimeMillis()),null,null);
        orderService.addOrder(order);
        order = orderService.getNewOrderByUserId(user.getUser_id());



        for (int k : cartGoodsList.keySet()) {
            CartGoods cartGoods = cartGoodsList.get(k);
            orderService.addOrderDetail(order.getOrder_id(),cartGoods);
        }

        req.getSession().removeAttribute("cartGoodsList");

            req.getRequestDispatcher("/pages/order/order.jsp?action=orderPlace").forward(req, resp);
        }
    }

    protected void getUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            User user = (User)req.getSession().getAttribute("_LOGIN_USER_");
            List<Address> addressList = userCenterService.getAddressByUserId(user.getUser_id());
            req.setAttribute("addressList",addressList);
            req.getRequestDispatcher("/pages/order/orderPlace.jsp").forward(req, resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void addOrUpdateUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String addressId = req.getParameter("myAddressModalAddressId");
        String addressProvince = req.getParameter("myAddressModalAddressProvince");
        String addressCity = req.getParameter("myAddressModalAddressCity");
        String addressArea = req.getParameter("myAddressModalAddressArea");
        String addressContent = req.getParameter("myAddressModalAddressContent");
        String addressReceiver = req.getParameter("myAddressModalAddressReceiver");
        String addressTel = req.getParameter("myAddressModalAddressTel");
        if (addressId.trim().length() == 0){
            User user = (User)req.getSession().getAttribute("_LOGIN_USER_");
            Address address = new Address(0,user.getUser_id(),addressProvince,addressCity,addressArea,addressContent,addressReceiver,addressTel,0);
            userCenterService.addAddress(address);
        }
        else {
            Address address = userCenterService.getAddressByAddressId(Integer.parseInt(addressId));
            address.setAddr_province(addressProvince);
            address.setAddr_city(addressCity);
            address.setAddr_area(addressArea);
            address.setAddr_content(addressContent);
            address.setAddr_receiver(addressReceiver);
            address.setAddr_tel(addressTel);
            userCenterService.updateAddress(address);
        }
    }

    protected void deleteUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int addressId = Integer.parseInt(req.getParameter("addressID"));
        userCenterService.deleteAddressByAddressId(addressId);
    }

    protected void defaultUserDeliveryAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int addressId = Integer.parseInt(req.getParameter("addressID"));
        User user = (User)req.getSession().getAttribute("_LOGIN_USER_");

        userCenterService.updateDefaultAddress(user.getUser_id(),addressId);

        resp.sendRedirect(req.getContextPath()+"/orders?action=getUserDeliveryAddress");
    }
}
